<template>
  <el-form :model="formModel" :rules="rules" ref="form" size="large" autocomplete="off">
    <el-form-item v-if="!isForgotPassword">
      <h2>登录</h2>
    </el-form-item>
    <el-form-item v-else>
      <h2>忘记密码</h2>
    </el-form-item>
    <el-form-item prop="username">
      <el-input v-model="formModel.username" :prefix-icon="User" placeholder="请输入用户名"></el-input>
    </el-form-item>
    <el-form-item v-if="!isForgotPassword" prop="password">
      <el-input v-model="formModel.password" name="password" :prefix-icon="Lock" type="password"
        placeholder="请输入密码"></el-input>
    </el-form-item>
    <el-form-item v-else prop="newPassword">
      <el-input v-model="formModel.newPassword" :prefix-icon="Lock" type="password" placeholder="请输入新密码"></el-input>
    </el-form-item>
    <el-form-item v-if="isForgotPassword" prop="confirmNewPassword">
      <el-input v-model="formModel.confirmNewPassword" :prefix-icon="Lock" type="password"
        placeholder="请再次输入新密码"></el-input>
    </el-form-item>
    <el-form-item v-if="!isForgotPassword" class="flex">
      <div class="flex">
        <el-checkbox>记住我</el-checkbox>
        <el-link type="danger" :underline="false" @click="isForgotPassword = true">忘记密码？</el-link>
      </div>
    </el-form-item>
    <el-form-item v-else>
      <el-button @click="resetPassword" class="button" type="danger" auto-insert-space>重置密码</el-button>
    </el-form-item>
    <el-form-item class="flex">
      <el-link type="info" :underline="false" @click="handleCancel">取消</el-link>
    </el-form-item>
    <el-form-item v-if="!isForgotPassword">
      <el-button @click="login" class="button" type="danger" auto-insert-space>登录</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { User, Lock } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/userStore';
import axios from 'axios';

const emit = defineEmits(['close']); // 显式声明 close 事件

const userStore = useUserStore();
const router = useRouter();
const form = ref();
const isForgotPassword = ref(false);

const formModel = ref({
  username: '',
  password: '',
  newPassword: '',
  confirmNewPassword: ''
});

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 10, message: '用户名必须是5-10位的字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的非空字符',
      trigger: 'blur'
    }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的非空字符',
      trigger: 'blur'
    }
  ],
  confirmNewPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的非空字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value !== formModel.value.newPassword) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// 初始化本地用户数据（可选）
const initLocalUsers = () => {
  axios.get('http://localhost:3000/users').then(response => {
    if (response.data.length === 0) {
      axios.post('http://localhost:3000/users', {
        username: 'admin',
        password: '123456',
        role: 'admin'
      });
    }
  });
};

onMounted(initLocalUsers);

// 登录功能
const login = async () => {
  await form.value.validate();
  try {
    const response = await axios.get(`http://localhost:3000/users?username=${formModel.value.username}&password=${formModel.value.password}`);
    if (response.data.length > 0) {
      const foundUser = response.data[0];
      userStore.setUser(foundUser);
      ElMessage.success('登录成功');
      localStorage.setItem('isLoggedIn', 'true');
      localStorage.setItem('userRole', foundUser.role); // 存储角色
      if (foundUser.role === 'admin') {
        router.push('/admin');
      } else {
        router.push('/main/home');
      }
      emit('close');
    } else {
      ElMessage.error('用户名或密码错误');
    }
  } catch (error) {
    ElMessage.error('登录失败，请稍后再试');
    console.error(error);
  }
};

// 忘记密码 - 重置密码功能
const resetPassword = async () => {
  await form.value.validate();
  try {
    const response = await axios.get(`http://localhost:3000/users?username=${formModel.value.username}`);
    if (response.data.length > 0) {
      const user = response.data[0];
      user.password = formModel.value.newPassword;
      await axios.put(`http://localhost:3000/users/${user.id}`, user);
      ElMessage.success('密码重置成功');
      isForgotPassword.value = false;
      emit('close');
    } else {
      ElMessage.error('用户名不存在');
    }
  } catch (error) {
    ElMessage.error('密码重置失败，请稍后再试');
    console.error(error);
  }
};

// 取消按钮逻辑
const handleCancel = () => {
  isForgotPassword.value = false;
  formModel.value.username = '';
  formModel.value.password = '';
  formModel.value.newPassword = '';
  formModel.value.confirmNewPassword = '';
  emit('close');
};
</script>

<style scoped>
/* 样式保持不变 */
.el-form {
  padding-top: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  width: 100%;
}

.el-form-item {
  width: 100%;
  margin-bottom: 20px;
}

.el-form-item:last-child {
  margin-bottom: 0;
}

.el-input {
  width: 100%;
}

.el-button {
  width: 100%;
}

.flex {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-checkbox {
  margin-right: 10px;
}

h2 {
  margin: 0 auto;
}
</style>